import { getScreenSize } from ".";
import { storeToRefs } from "pinia";
import { globalScale } from "@/config/static";
import { useMapStore } from "@/store/mapStore";
import { useUserStore } from "@/store/userStore";
import { SceneType, useSceneStore } from "@/store/sceneStore";
import { useCameraStore } from "@/store/cameraStore";

/**
 * 更新相机位置
 * @param ctx 画布上下文
 */
export const updateCamera = (ctx: CanvasRenderingContext2D) => {
  const mapStore = useMapStore();
  const userStore = useUserStore();
  const sceneStore = useSceneStore();
  const currentScene = sceneStore.currentScene;
  const { playerPosition } = storeToRefs(userStore);
  const { mapPixelWidth, mapPixelHeight } = storeToRefs(mapStore);
  const { width: screenWidth, height: screenHeight } = getScreenSize();

  const canvas = ctx.canvas;

  if (!canvas) return;

  // 在房屋内部场景时，使用固定相机位置
  if (currentScene === SceneType.HOUSE) {
    // 获取当前地图的实际尺寸
    const mapWidth = mapStore.mapPixelWidth;
    const mapHeight = mapStore.mapPixelHeight;

    const offsetX = Math.floor((screenWidth / globalScale - mapWidth) / 2);
    const offsetY = Math.floor((screenHeight / globalScale - mapHeight) / 2);

    ctx.translate(offsetX, offsetY);
    return;
  }

  // 计算相机中心点
  const viewPortCenterX = ctx.canvas.width / 2 / globalScale;
  const viewPortCenterY = ctx.canvas.height / 2 / globalScale;

  // 计算最大滚动距离 = 地图宽度 - 视口宽度
  const maxScrollX = Math.max(
    0,
    mapPixelWidth.value - ctx.canvas.width / globalScale
  );

  const maxScrollY = Math.max(
    0,
    mapPixelHeight.value - ctx.canvas.height / globalScale
  );

  // 目前滚动位置-水平
  let horizontalScrollDistance = Math.floor(
    Math.max(0, playerPosition.value.x - viewPortCenterX)
  );
  horizontalScrollDistance = Math.min(horizontalScrollDistance, maxScrollX);

  // 目前滚动位置-垂直
  let verticalScrollDistance = Math.floor(
    Math.max(0, playerPosition.value.y - viewPortCenterY)
  );

  // 确保不会超过最大滚动距离
  verticalScrollDistance = Math.min(verticalScrollDistance, maxScrollY);

  ctx.translate(-horizontalScrollDistance, -verticalScrollDistance);

  useCameraStore().cameraOffset = {
    x: horizontalScrollDistance,
    y: verticalScrollDistance,
  };
};
